﻿using SSharing.Frameworks.Common.Extends;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConcurrentTools
{
    public class Config
    {
        public string Url { get; set; }
        public string Head { get; set; }
        public string Body { get; set; }

        public static MethodResult<Config> Load(string path)
        {
            if (!File.Exists(path))
            {
                return new MethodResult<Config>(false, "路径不存在");
            }
            var content = File.ReadAllText(path);
            try
            {
                var data = content.FromJson<Config>();
                if (data == null)
                {
                    return new MethodResult<Config>(false, "读取配置失败");
                }
                return MethodResult.CreateRst(true, "成功", data);
            }
            catch (Newtonsoft.Json.JsonReaderException ex)
            {
                return new MethodResult<Config>(false, string.Format("配置内容有误，错误：{0}", ex.Message));
            }
            catch (Exception ex)
            {
                return new MethodResult<Config>(false, ex.Message);
            }
        }

        public static MethodResult Save(Config config, string path)
        {
            if (config == null)
            {
                return new MethodResult(false, "config 不能为空");
            }
            var json = config.ToJson();
            File.WriteAllText(path, json);
            return MethodResult.Success;
        }
    }
}
